<template>
  <div class="login-form-container">
    <div class="logo">
      <img src="@/assets/images/logo.png" width="240px" />
    </div>
    <el-form ref="ruleFormRef" :model="ruleForm" :rules="rules" size="large">
      <el-form-item prop="account">
        <el-input v-model="ruleForm.account" placeholder="请输入用户名">
          <template #prefix>
            <el-icon class="el-input__icon">
              <User />
            </el-icon>
          </template>
        </el-input>
      </el-form-item>
      <el-form-item prop="password">
        <el-input v-model="ruleForm.password" type="password" placeholder="请输入密码" show-password autocomplete="new-password">
          <template #prefix>
            <el-icon class="el-input__icon">
              <lock />
            </el-icon>
          </template>
        </el-input>
      </el-form-item>
      <el-form-item prop="code" class="form-item-code">
        <el-input v-model="ruleForm.code" placeholder="请输入验证码">
          <template #prefix>
            <el-icon><Picture /></el-icon>
          </template>
          <template #append>
            <img :src="'data:image/png;base64,' + ruleForm.imgcode" alt="" @click="getCode" width="145px" height="38px" />
          </template>
        </el-input>
      </el-form-item>
    </el-form>
    <div class="login-btn" :style="{ backgroundColor: DEFAULT_PRIMARY }" @click="handleLogin(ruleFormRef)">登 录</div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from "vue"
import { useRouter } from "vue-router"
import { loginApi, getCodeApi } from "@/api/modules/login"
import { useUserStore } from "@/stores/modules/user"
import { useTabsStore } from "@/stores/modules/tabs"
import { useAuthStore } from "@/stores/modules/auth"
import { useKeepAliveStore } from "@/stores/modules/keepAlive"
import { initDynamicRouter } from "@/routers/modules/dynamicRouter"
import type { ElForm } from "element-plus"
import { encryptDes } from "@/utils/des"
import { ElMessage } from "element-plus"
import { DEFAULT_PRIMARY } from "@/config"

const router = useRouter()

const userStore = useUserStore()
const tabsStore = useTabsStore()
const keepAliveStore = useKeepAliveStore()

interface RuleForm {
  account: string
  password: string
  code: string
  uuid: string
  imgcode: string
}
type FormInstance = InstanceType<typeof ElForm>
const ruleFormRef = ref<FormInstance>()
const rules = reactive({
  account: [{ required: true, message: "请输入用户名", trigger: "blur" }],
  password: [{ required: true, message: "请输入密码", trigger: "blur" }],
  code: [{ required: true, message: "请输入验证码", trigger: "blur" }]
})
const loading = ref(false)
const ruleForm = reactive<RuleForm>({
  account: "admin",
  password: "123456",
  code: "",
  uuid: "",
  imgcode: ""
})

/** 获取 验证码 */
const getCode = async () => {
  const { data } = await getCodeApi()
  ruleForm.imgcode = data.codeImg
  ruleForm.uuid = data.uuid
}
/** 登录 */
const handleLogin = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.validate(async valid => {
    if (!valid) return
    loading.value = true
    try {
      // 1.执行登录接口
      loginApi({ ...ruleForm, password: encryptDes(ruleForm.password) })
        .then(async res => {
          const info = { ...res.data.user, roleList: res.data.roleList, deptList: res.data.deptList }
          userStore.setUserInfo(info)
          userStore.setToken(res.data.token)
          // 2.添加动态路由
          await initDynamicRouter()
          // 3.清空 tabs、keepAlive 数据
          tabsStore.setTabs([])
          keepAliveStore.setKeepAliveName([])
          // 4.跳转到首页
          // router.replace("/home/index")
          // 4.如果路由权限有大屏菜单权限且为显示状态，跳转到大屏，若无则跳转到第一个有效菜单
          const authStore = useAuthStore()
          const { authMenuList } = authStore
          const hasScreen = authMenuList.find(e => e.path === "/home" && !e.meta.isHide)
          if (hasScreen) {
            router.replace("/home")
          } else {
            const firstPath = findFirstPath(authMenuList)
            if (firstPath) {
              router.replace(firstPath)
            } else {
              ElMessage.error("当前角色未配置有效路径")
            }
          }
        })
        .catch(() => {
          getCode()
          loading.value = false
        })
    } finally {
      loading.value = false
    }
  })
}
/** 递归寻找第一个有效路径 */
const findFirstPath = (menus: Menu.MenuOptions[]): string | null => {
  for (const item of menus) {
    // 如果组件为Layout 或未设置组件 或未设置路径 或隐藏，尝试子菜单
    if (item.component === "Layout" || !item.component || !item.path || item.meta.isHide) {
      if (item.children && item.children.length > 0) {
        const result = findFirstPath(item.children)
        if (result) return result
      }
    } else {
      return item.path
    }
  }
  return null
}
onMounted(() => {
  getCode()
  // 监听键盘 enter 事件
  document.onkeydown = (e: KeyboardEvent) => {
    e = (window.event as KeyboardEvent) || e
    if (e.code === "Enter" || e.code === "enter" || e.code === "NumpadEnter") {
      if (loading.value) return
      handleLogin(ruleFormRef.value)
    }
  }
})
</script>

<style scoped lang="scss">
.login-form-container {
  padding: 50px 0;
  .logo {
    display: flex;
    align-items: center;
    justify-content: center;
    margin-bottom: 40px;
  }
  .el-form {
    .el-form-item {
      :deep(.el-form-item__content) {
        .el-input {
          .el-input__wrapper {
            background-color: #f2f3f5;
            border: 0;
            box-shadow: none;
          }
        }
      }
    }
    .form-item-code {
      :deep(.el-form-item__content) {
        .el-input {
          .el-input-group__append {
            padding: 0 1px 0 10px;
            background-color: inherit;
            box-shadow: none;
          }
        }
      }
    }
  }
  .login-btn {
    box-sizing: border-box;
    display: flex;
    align-items: center;
    justify-content: center;
    width: 100%;
    height: 42px;
    margin-top: 40px;
    color: #ffffff;
    cursor: pointer;
    border-radius: 10px;
  }
}
</style>
